import sqlite3 as sql
import subprocess, traceback

# get all maps in database 
def getmaps(database):
    output = []
    con  = sql.connect(database)
    with con:
        cursor = con.cursor()
        try:
            cursor.execute("select distinct mapid from Cts_times;")
            output = cursor.fetchall()
        except sql.Error:
            print("Shit is fucked.")
    return output

# if there is no query then it outputs the index file.
def getcontent(query=None):
    cmd  = [("./cts")]
    proc = subprocess.Popen(cmd, env=query, stdout=subprocess.PIPE, shell=True)
    # communicate returns 'bytes' class with function 'decode'
    return proc.communicate()[0].decode('utf-8')

def renderindex(template):
    # no env variable
    table = getcontent()
    filename = "./output/index.html"
    with open(filename, 'w+') as fout:
        fout.write(template % (table))
        fout.close
    pass

def main():
    template = ""
    with open("overview.html", 'r') as fin:
        template = fin.read()
    renderindex(template)
    maps  = getmaps("db/cts.db")
    with open("map.html", 'r') as fin:
        template = fin.read()
    # for each map generate an html file.
    for game_map in maps:
    # game_map is a tuple obj.
        map_name = game_map[0]
        query    = {"QUERY_STRING" : ("map=%s" % map_name)}
        table    = getcontent(query)
        filename = ("./output/maps/%s.html" % map_name)
        with open(filename, 'w+') as fout:
            title = map_name
            fout.write(template.format(
                title=title, 
                map_name=map_name, 
                table=table)
            )
            # fout.write(template % (title, map_name, table))
    return True

if __name__ == "__main__":
    success = False
    try:
        success = main()
    except FileNotFoundError:
        traceback.print_exc()
        print("\n\t The script probably didn't find the page templates needed to generate a page. You can copy minimal working examples from the repository at templates/.")
    if success:
        print("allmaps.py - Generated pages for all maps.")
    pass
